﻿import { Injectable } from '@angular/core';
import { Http, URLSearchParams, Headers, Response, RequestOptions, RequestMethod } from '@angular/http';

import { Events } from 'ionic-angular';

import { Subscriber } from 'rxjs/Subscriber';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

/*
  Generated class for the ServerHttpProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class ServerHttp {
    private _serve = 'http://112.74.44.31:8056';

    private _error: number = 0;
    private _interval: number = 0;

    constructor(
        private http: Http,
        private events: Events) {
    }

    /** 用户信息 */
    get userinfo(): UserInfo {
        let _ui = window.sessionStorage['userinfo'];

        if (_ui && _ui != 'null' && _ui != 'undefined' && _ui != 'false') {
            return JSON.parse(_ui);
        } else {
            return undefined;
        }

    }

    set userinfo(val: UserInfo) {
        let _ui = JSON.stringify(val);

        if (_ui && _ui != 'null' && _ui != 'undefined' && _ui != 'false') {
            window.sessionStorage['userinfo'] = _ui;
        } else {
            window.sessionStorage['userinfo'] = '';
        }
    }

    /** 用户账号 */
    get account(): string {
        return window.localStorage['account'];
    }

    set account(val: string) {
        window.localStorage['account'] = val || '';
    }

    /** 用户密码 */
    get password(): string {
        return window.localStorage['password'];
    }
    set password(val: string) {
        window.localStorage['password'] = val || '';
    }

    /** 登录授权码*/
    get token(): string {
        return window.sessionStorage['token'];
    }

    set token(val: string) {
        window.sessionStorage['token'] = val || '';
    }

    /** 自动登录标识 */
    get autoLogin(): boolean {
        let account = this.account;
        let password = this.password;
        let autoLogin = window.localStorage['autoLogin'];

        return !!('true' === autoLogin && account && password);
    }

    set autoLogin(val: boolean) {
        window.localStorage['autoLogin'] = (val ? 'true' : 'false');
    }

    /**
    * 是否已登录
    */
    get isLogin(): boolean {
        return !!(this.token);
    }

    /**
     * 返回 - 当前服务器配置
     */
    get serve() {
        return this._serve;
    }

    /**
     * get - 请求数据
     * @param url
     * @param options
     */
    get(url: string, options?: RequestOptions): Observable<Response> {
        return this.http.get(url, options);
    }
    /**
     * post - 请求数据
     * @param url
     * @param body
     * @param options
     */
    post(url: string, body: any, options?: RequestOptions): Observable<Response> {
        return this.http.post(url, body, options);
    }

    /**
     * 退出登录
     * @param autoLogin
     */
    logout(autoLogin?: boolean) {
        // 清空登录数据
        this.token = undefined;
        this.userinfo = undefined;
        this.autoLogin = autoLogin;
        // 取消心跳发送
        clearInterval(this._interval);
        // 发布退出登录事件
        this.events.publish('login:logout');
    }
    /**
    * 加入登录验证的GET请求
    * @param url
    */
    public httpGetWithAuth(url: string, param?: any): Observable<any> {
        let params = new URLSearchParams();
        for (var key in param) {
            params.set(key, param[key]);
        }

        let options = new RequestOptions({
            search: param,
            method: RequestMethod.Get,
            headers: new Headers({
                'Authorization': this.token,
                'Content-Type': 'application/json;charset=utf-8'
            })
        });

        return this.xhr(url, options);
    }

    /**
     * 不加登录验证的GET请求
     * @param url
     */
    public httpGetNoAuth(url: string, param?: any): Observable<any> {
        let params = new URLSearchParams();
        for (var key in param) {
            params.set(key, param[key]);
        }

        let options = new RequestOptions({
            search: param,
            method: RequestMethod.Get,
            headers: new Headers({
                'Content-Type': 'application/json;charset=utf-8'
            })
        });

        return this.xhr(url, options);
    }

    /**
    * 加入登录验证的POST请求
    * @param url
    * @param body
     */
    public httpPostWithAuth(url: string, body?: any): Observable<any> {
        let options = new RequestOptions({
            body: body || {},
            method: RequestMethod.Post,
            headers: new Headers({
                'Authorization': this.token,
                'Content-Type': 'application/json;charset=utf-8'
            })
        });

        return this.xhr(url, options);
    }

    /**
     * 不加登录验证的POST请求
     * @param url
     * @param body
     */
    public httpPostNoAuth(url: string, body?: any): Observable<any> {
        let options = new RequestOptions({
            body: body || {},
            method: RequestMethod.Post,
            headers: new Headers({
                'Content-Type': 'application/json;charset=utf-8'
            })
        });

        return this.xhr(url, options);
    }

    private xhr(url: string, options: RequestOptions): Observable<any> {
        return Observable.create((observer: Subscriber<any>) => {
            this.http.request(this._serve + url, options).subscribe((res) => {
                let result = res.json();
                // 判断返回的success 标识是否为正确
                if (result.success) {
                    observer.next(result);
                } else {
                    observer.error(result);
                }
            }, (err) => {
                observer.error(err);
            }, () => {
                observer.complete();
            });
        });
    }

}
/**
* 用户信息
**/
export interface UserInfo {
    /**用户名(账号)*/
    username?: string;
    /**用户姓名*/
    realname?: number;
    /**用户编号*/
    userCode?: number;
    /**用户等级*/
    level?: string;
    /**用户等级名*/
    levelName?: number;
    /**用户联系方式*/
    contact?: number;
    /**用户性别*/
    sex?: string;
    /**用户性别名*/
    sexName?: string;
    /**用户区域*/
    area?: any;
    /**用户区域名*/
    areaName?: number;
    /**登录时间*/
    addtime?: string;
    /**最后活动时间*/
    lasttime?: string;
}
export class PageInfo {
    private _page: number = 1;
    private _pageSize: number = 20;
    private _hasNextPage: boolean;

    private _items: Array<any> = [];

    /** 数据集 */
    get Items(): any[] {
        return this._items;
    }
    set Items(val: any[]) {
        this._items = val;
    }
    /** 当前页码 */
    get Page(): number {
        return this._page;
    }
    set Page(val: number) {
        this._page = val;
    }
    /** 下一页,页码 */
    get NextPage(): number {
        return (this.Page + 1);
    }
    /** 每页条数 */
    get PageSize(): number {
        return this._pageSize;
    }
    set PageSize(val: number) {
        this._pageSize = val;
    }
    /** 是否有下一页 */
    get HasNextPage(): boolean {
        return this._hasNextPage;
    }
    set HasNextPage(val: boolean) {
        this._hasNextPage = val;
    }

    constructor() {
    }

    /**
     * 添加多条数据
     * @param arr 数据集
     * @param ref 是否刷新 
     * @param hasNextPage 是否有下一页
     */
    addAll(arr: any[], ref?: boolean, hasNextPage?: boolean) {
        if (ref) {
            this._page = 1;
            this._items = arr;
            this._hasNextPage = hasNextPage || true;
        } else {
            this._page++;
            this.concat(arr);
            this._hasNextPage = hasNextPage || true;
        }
    }

    /**
     * 添加单条数据
     * @param item
     */
    add(item: any) {
        if (!item) return;

        this._items.push(item);
    }

    /**
     * 合并数据
     * @param arr
     */
    concat(arr: any[]) {
        if (!arr || arr.length <= 0) return;

        // 将数据追加进数据集
        arr.forEach((val) => {
            this._items.push(val);
        });
    }
}